<template>
  <div class="post-editor">
    <div class="post-info">
      <el-page-header @back="backToHome">
        <template #content>
          <div class="flex items-center">
            <span class="text-large font-600 mr-3" v-if="query.edit">编辑博文</span>
            <span class="text-large font-600 mr-3" v-else>新增博文</span>
            <el-tag style="margin-left: 10px" v-if="post.status === 0" type="info">草稿</el-tag>
            <el-tag style="margin-left: 10px" v-if="post.status === 1" type="success">发布</el-tag>
            <el-tag style="margin-left: 10px" v-if="post.status === 2" type="danger">加密</el-tag>
            <el-tag style="margin-left: 10px" v-if="post.status === 3" type="warning">置顶</el-tag>
          </div>

        </template>
        <template #extra>
          <div class="flex items-center">
            <el-button type="primary" @click="save">保存</el-button>
            <el-button type="info" @click="preview" >预览</el-button>
            <el-button v-if="post.status == 1" type="warning" @click="updateStatus('3')">置顶</el-button>
            <el-button v-else-if="post.status == 3" type="info" @click="updateStatus('1')">取消置顶</el-button>
            <el-button v-if="post.status != 0" type="danger" @click="updateStatus('0')">取消发布
            </el-button>
            <el-button type="success" @click="updateStatus('1')" :disabled="!post.id" v-else> 发布</el-button>
          </div>
        </template>
        <div class="post-info-item">
          <el-form :label-position="'left'" :model="post" ref="ruleFormRef1" label-width="50px" status-icon>
            <el-form-item size="large" label="标题">
              <el-input v-model="post.title" />
            </el-form-item>
            <el-form-item size="large" label="摘要">
              <el-input type="textarea" v-model="post.excerpt" />
            </el-form-item>
          </el-form>
          <el-form class="demo-form-inline" :label-position="'left'" :inline="true" :model="post" ref="ruleFormRef2"
            label-width="50px" status-icon>
            <el-form-item size="large" label="日期">
              <el-input label="ceshi" disabled v-model="pubDate" />
            </el-form-item>
            <el-form-item size="large" label="分类">
              <el-select  
                clearable  
                allow-create
                filterable
                :reserve-keyword="false"
                v-model="post.category"   
                placeholder="Select" 
                style="width: 240px">
                <el-option v-for="item in categoryList.list" :key="item.id" :label="item.name" :value="item.name" />
              </el-select>
            </el-form-item>
            <el-form-item  size="large" label="标签">
              <el-select  
                v-model="post.tags" 
                allow-create 
                filterable 
                multiple
                :reserve-keyword="false"
                placeholder="Select" 
                style="width: 350px">
                <el-option v-for="item in tagList.list" :key="item.id" :label="item.name" :value="item.name" />
              </el-select>
            </el-form-item>
          </el-form>
        </div>
      </el-page-header>
    </div>

    <MdEditor v-model="post.content" :previewTheme="state.theme" />
  </div>
</template>

<script setup>
import { MdEditor } from 'md-editor-v3';
import 'md-editor-v3/lib/style.css';
import { onMounted, reactive, ref } from "vue";
import { useRoute, useRouter } from "vue-router";
import { getPost, savePost, updatePost,patchPost } from "@/api/admin";
import { dateFormat } from "@/utils/utils";
import { categoryList, tagList } from '@/store/customer/inedx'
import { ElMessage } from 'element-plus'
import {postPreview} from "@/store/admin/index";
import router from "@/router/index";
const { query } = useRoute()  //2.在跳转页面定义router变量，解构得到指定的query和params传参的参数
const pubDate = ref('')

const post = ref({
  id: null,
  title: null,
  excerpt: null,
  content: '',
  pub_date: null,
  category: null,
  tags: [],
  status: 0,
})

const state = reactive({
  id: 'my-editor',
  theme: 'vuepress',
  showCodeRowNumber: true,
  catalogList: []
});

onMounted(() => {
  if (query.edit||postPreview!=null) {
    loadPost()
  }
})

function handleBeforeSave(){
  let postData = JSON.parse(JSON.stringify(post.value));
  //需要把select组件的格式转换成django能识别的格式
  var tags = []
  postData.tags.forEach(item => {
    tags.push({id:1,'name': item })
  });
  postData.tags = tags
  //类别信息也要转换
  if (post.value.category !== null&&post.value.category !== "") {
    postData.category = {id:1,'name': post.value.category }
  } else {
    postData.category = {id:1,'name': '未分类' }
  }
  return postData
}

function save() {
  let postData = handleBeforeSave()
  if (query.edit) {
    updatePost(postData, postData.id).then((res) => {
      ElMessage({
        message: '保存成功',
        type: 'success',
      })
    }).catch((error) => {
      ElMessage({
        message: error,
        type: 'danger',
      })
    });
  } else {
    savePost(postData).then((res) => {
      ElMessage({
        message: '保存成功',
        type: 'success',
      })
      console.log(res.data)
      dataFormat(res.data)
    }).catch((error) => {
      console.log
      ElMessage({
        message: error,
        type: 'error',
      })
    });
  }
  postPreview.value = null;
}
function loadPost() {
  if(query.edit){
    getPost(query.id).then((res) => {
      dataFormat(res.data)
    })
  }else if(postPreview.value!=null){
    let data = JSON.parse(JSON.stringify(postPreview.value))
    dataFormat(data)
  }
}
function updateStatus(sta){
  let data = null;
  if(sta==="3"){
    data = {status:sta,is_top : true}
  }else{
    data = {status:sta,is_top : false}
  }
  patchPost(data,post.value.id).then((res) => {
      ElMessage({
        message: '操作成功',
        type: 'success',
      })
      dataFormat(res.data)
    }).catch((error) => {
      ElMessage({
        message: error,
        type: 'error',
      })
    });
}
function dataFormat(data) {
  post.value = data;
  pubDate.value = dateFormat(data.pub_date)
  var tags = []
  data.tags.forEach(item => {
    tags.push(item.name)
  })
  post.value.tags = tags
  if (data.category != null) {
    post.value.category = data.category.name
  }
}
function backToHome() {
  router.back()
}
function preview() {
  let postData = handleBeforeSave()
  postPreview.value = postData;
  router.push({path:'/post',query: {preview:true} })
}
</script>

<style scoped>
.md-editor {
  margin-left: 20px;
  max-width: 1600px;
  height: 900px;
}

.post-editor {
  padding: 20px 20px 0px 20px;
  width: 100%;
}

.post-info {
  margin-left: 20px;
}

.post-info-item {
  margin-top: 20px;
  width: 100%;
}

.demo-form-inline .el-input {
  --el-input-width: 300px;
}

.demo-form-inline .el-select {
  --el-select-width: 220px;
}
</style>